package com.taotao.sso.service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.sso.mapper.UserMapper;
import com.taotao.sso.pojo.TbUser;
import com.taotao.sso.service.RedisService;

@Service
public class UserService {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RedisService redisService;
	
	private static final String TOKEN = "TOKEN:PHF:";
	
	private static final Integer EXPIRE_TIME = 60*60*24*30;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	
	private static final Map<Integer, Boolean> TYPE = new HashMap<Integer, Boolean>();
	static{
		TYPE.put(1, true);
		TYPE.put(2, true);
		TYPE.put(3, true);
	}
	
	public Boolean check(String param, Integer type) {
		 if(!TYPE.containsKey(type)){
			 return null;
		 }
		 TbUser record = new TbUser();
		 switch(type){
			 case 1 :
				 record.setUsername(param);
				 break;
			 case 2 :
			     record.setPhone(param);
			     break;
			 case 3 :
				 record.setEmail(param);
		 }
		TbUser user = userMapper.selectOne(record);
		return null != user;
	}
	
	public Boolean save(TbUser user) {
		user.setId(null);
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		return 1 == userMapper.insert(user);
	}
	
	public String doLogin(TbUser user) throws JsonProcessingException {
		TbUser tempUser = new TbUser();
		tempUser.setUsername(user.getUsername());
		tempUser = userMapper.selectOne(tempUser);
		if(tempUser == null) {
			return null;
		}
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		if(StringUtils.equals(user.getPassword(), tempUser.getPassword())){
			String token = DigestUtils.md5Hex(String.valueOf(tempUser.getId()));
			redisService.set(TOKEN + token,
					         MAPPER.writeValueAsString(tempUser),
					         EXPIRE_TIME);
			return token;
		}
		
		return null;
	}

	public TbUser queryUserByToken(String token)  {
		String key = TOKEN + token;
		try {
			String data = redisService.get(key);
			TbUser user = MAPPER.readValue(data, TbUser.class);
			if(user != null){
				redisService.expire(key, EXPIRE_TIME);
			}
			return user;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
